//
//  TabBarView.swift
//  SwiftProject
//
//  Created by wwj on 16/2/23.
//  Copyright © 2016年 wwj. All rights reserved.
//

import UIKit
//MARK: 代理方法
@objc protocol TabBarViewDelegate: NSObjectProtocol{
    optional
    func onClickTabBarView(tabBarView:TabBarView, index:NSInteger)
}

class TabBarView: UIView {
    var selectBtn:TabBarButton?
    weak var delegate: TabBarViewDelegate?
    
    func addTabBarButtonWith(title:String, image:String, selectImage:String){
        let barItemBtn = TabBarButton()
        barItemBtn.setTitle(title, forState: UIControlState.Normal)
        barItemBtn.setImage(UIImage(named: image), forState: UIControlState.Normal)
        barItemBtn.setImage(UIImage(named: selectImage), forState: UIControlState.Selected)
        barItemBtn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        barItemBtn.titleLabel?.font = UIFont.systemFontOfSize(13)
        barItemBtn.addTarget(self, action: Selector("onClickBtn:") , forControlEvents: UIControlEvents.TouchDown)
        self.addSubview(barItemBtn)
    }
    
     func onClickBtn(btn:TabBarButton){
        addAnimation(btn.imageView!)
        delegate?.onClickTabBarView!(self, index: btn.tag)
        selectBtn?.selected = false
        btn.selected = true
        selectBtn = btn
       
        
    }
    
    //MARK: 添加动画
    private func addAnimation(imageView:UIImageView){
        let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
        bounceAnimation.duration = NSTimeInterval(0.6)
        bounceAnimation.calculationMode = kCAAnimationCubic
        imageView.layer.addAnimation(bounceAnimation, forKey: "bounceAnimation")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let buttonW = CGFloat(self.frame.size.width) / CGFloat(self.subviews.count)
        let buttonH = self.frame.size.height
        for (var index = 0; index<self.subviews.count; index++){
            let button = self.subviews[index]
            let buttonX = buttonW * CGFloat(index)
            button.frame = CGRectMake(buttonX, 0, buttonW, buttonH)
            button.tag = index
            if(index == 0){
                onClickBtn(button as! TabBarButton)
            }
        }
    }

}
